<style lang="less">
  .charge-offs-list {
    .el-form--inline .el-form-item {
      margin-bottom: 10px;
      margin-right: 0px;
    }
  }
</style>
<template>
  <el-dialog  width="1200px" title="可销账账单" :show-close="false" :visible.sync="dialogVisible" class="charge-offs-list">
    <el-row v-if="isList">
      <search-bar>
        <el-form label-width="80px">
          <el-row>
            <el-col :span="10">
              <el-form-item label="账单周期">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  placeholder="">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!--<el-col :span="7">-->
              <!--<el-form-item labelWidth="0px">-->
                <!--<el-select v-model="monthDateRange" placeholder="账单周期按月选择">-->
                  <!--<el-option-->
                    <!--v-for="item in allMonthDateRange"-->
                    <!--:key="item.value"-->
                    <!--:label="item.label"-->
                    <!--:value="item.value">-->
                    <!--<span style="float: left">{{ item.label }}</span>-->
                    <!--<span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>-->
                  <!--</el-option>-->
                <!--</el-select>-->
              <!--</el-form-item>-->
            <!--</el-col>-->
          </el-row>
        </el-form>
      </search-bar>
      <el-col :span="24" style="margin-bottom: 10px">
        <el-button type="primary" @click="resetSearchCondition" style="float: right">重置</el-button>
        <el-button type="primary" @click="searchTableList" style="float: right;margin-right: 10px">查询</el-button>
      </el-col>

      <el-table :data="tableData" border tooltip-effect="dark" style="width: 100% ;margin-top: 10px"
                @sort-change="sortChange"
                @selection-change="selsChange" v-loading="listLoading">
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column prop="truckLoadNumber" label="订单编号" width="150" align="center">
          <template slot-scope="scope">
            <a style="cursor: pointer;text-decoration:underline;color: #20a0ff">
              {{scope.row.truckLoadNumber}}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="createdDate" label="日期" width="200" headeer-align="center">
          <template slot-scope="scope">
            下单日期 {{scope.row.createdDate}}<br>
            卸车时间 {{scope.row.unloadTime}}
          </template>
        </el-table-column>
        <el-table-column prop="startContactName" label="发货人" width="100" headeer-align="center">
          <template slot-scope="scope">
            {{scope.row.startContactName}}<br>
            {{scope.row.startContactPhone}}
          </template>
        </el-table-column>
        <el-table-column prop="driverName" label="司机信息" width="100" header-align="center">
          <template slot-scope="scope">
            {{scope.row.driverName}}<br>
            {{scope.row.driverPhone}}<br>
            {{scope.row.plateNumber}}
          </template>
        </el-table-column>
        <el-table-column prop="cargoName" label="货物信息" width="100;" header-align="center">
        <template slot-scope="scope">
        {{scope.row.cargoName}}<br>
        {{scope.row.weight}} 吨 |
        {{scope.row.volume}} 方
        </template>
        </el-table-column>
        <el-table-column prop="orderAmt" label="运费(元)" width="80" header-align="center">
        </el-table-column>
        <el-table-column prop="infofeeAmt" label="信息费(元)" width="80" header-align="center">
        </el-table-column>
        <el-table-column prop="incomeAmt" label="收益金额(元)" width="100" header-align="center">
        </el-table-column>
        <el-table-column prop="orderStatusName" label="订单状态" width="80" header-align="center">
        </el-table-column>
        <el-table-column prop="writeOffStatusName" label="销账状态" width="120" header-align="center">
        </el-table-column>
      </el-table>
      <el-row>
        <el-col :span="24" class="toolbar">
          <el-col :span="12">
            <div class="statistics">
              合计：
              票数合计 <span style="color: red">{{totalIncomeInfo.totalOrderNum}}</span> 元，
              运费合计 <span style="color: red">{{totalIncomeInfo.totalOrderAmt}}</span> 元，
              信息费合计 <span style="color: red">{{totalIncomeInfo.totalInfofeeAmt}}</span> 元，
              收益合计 <span style="color: red">{{totalIncomeInfo.totalIncomeAmt}}</span> 元
            </div>
          </el-col>
          <el-col :span="12">
            <div style="width:200px;float: right">
              <el-button type="primary" @click="openChargeOffs" :disabled="isAbleToOpenChargeOffs" style="margin-left: 20px">一键销账</el-button>
              <el-button @click="closeChargeOffsList" style="margin-left: 20px">取消</el-button>
            </div>
          </el-col>
        </el-col>
      </el-row>

      <el-col :span="24" class="toolbar" style="margin-top: 5px">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total,sizes,prev, pager, next, jumper"
          :total="total" style="text-align: center;background-color: white">
        </el-pagination>
      </el-col>
    </el-row>
    <el-row v-if="isList === false">
      <!--销账确认-->
      <el-form :model="objInfo" label-position="right" label-width="140px" ref="objInfo" :rules="objInfoRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="领头羊:">
              <el-input v-model="truckBellwetherName" :disabled="true" style="width: 330px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单周期:">
              <el-input v-model="objInfo.billingCycle" :disabled="true" style="width: 330px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单数量(票):">
              <el-input v-model="totalIncomeInfo.totalOrderNum" :disabled="true" style="width: 330px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单信息费(元):">
              <el-input v-model="totalIncomeInfo.totalOrderAmt" :disabled="true" style="width: 330px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="border-bottom: 1px solid lavender">
          <el-col :span="12">
            <el-form-item label="收益金额(元):">
              <el-input v-model="totalIncomeInfo.totalIncomeAmt" :disabled="true" style="width: 330px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可销账收益金额(元):">
              <el-input v-model="totalIncomeInfo.totalIncomeAmt" :disabled="true" style="width: 330px;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 15px">
          <el-col :span="24">
            <el-form-item label="付款时间" prop="chargeOffsTime">
              <el-date-picker v-model="objInfo.chargeOffsTime"  style="width: 550px"
                              type="datetime"
                              placeholder="">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="到账银行" prop="bankName">
              <el-input v-model="objInfo.bankName"  style="width: 550px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="银行卡号" prop="bankNum">
              <el-input v-model="objInfo.bankNum"  style="width: 550px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="银行户名" prop="accountName">
              <el-input v-model="objInfo.accountName"  style="width: 550px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="银行流水号" prop="serialNum">
              <el-input v-model="objInfo.serialNum"  style="width: 550px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" :rows="3" v-model="objInfo.remark" style="width: 550px" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传凭证" prop="fileList">
              <el-upload
                list-type="picture-card"
                action="/api/v3.0/admin/api/truck-bellwether-write-offs/file_upload"
                :headers="this.$store.state.headersAuthorization"
                :limit="5"
                :on-exceed="handleExceed"
                :before-upload="beforeUploadImg"
                :on-change="handleChange"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-form-item style="text-align: right">
            <el-button @click.native="closeInfoChargeOffs">关闭</el-button>
            <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">保存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  searchTruckBellwetherAcctTFlowList, searchTruckBellwetherAcctTFlowListSum, saveTruckBellwetherWriteOff } from '../../../api/v3/TruckLoadProfit';
import { resetObjNull } from '../../../lib/util.js';

export default {
  name: 'ChargeOffsList',
  componentName: 'ChargeOffsList',
  props: {
    loadData: Function
  },
  data () {
    return {
      // 可销账列表
      isList: true,
      truckBellwetherId: null,
      truckBellwetherName: null,
      totalIncomeInfo: {
        'truckBellwetherTflowIds': null,
        'totalOrderNum': 0,
        'totalOrderAmt': 0.00,
        'totalInfofeeAmt': 0.00,
        'totalIncomeAmt': 0.00
      },
      dialogVisible: false,
      searchCondition: {
        'GTE_truckLoadOrder.unloadTime': null, // 卸车时间
        'LTE_truckLoadOrder.unloadTime': null
      },
      dateRange: [], // 卸车时间范围
      // monthDateRange: null,
      // allMonthDateRange: [],
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'createdDate',
      sortOrder: 'descending',
      listLoading: false,

      // 销账操作
      isAbleToOpenChargeOffs: true, // 是否可一键销账操作
      submitLoading: false,
      billingCycle: null, // 销账周期
      fileList: [],
      objInfo: {},
      objInfoRules: {
        chargeOffsTime: [
          {required: true, message: '请输入付款时间', trigger: 'blur'}
        ],
        bankName: [
          {required: true, message: '请输入到账银行', trigger: 'blur'}
        ],
        bankNum: [
          {required: true, message: '请输入银行卡号', trigger: 'blur'}
        ],
        accountName: [
          {required: true, message: '请输入银行户名', trigger: 'blur'}
        ],
        serialNum: [
          {required: true, message: '请输入银行流水号', trigger: 'blur'}
        ]
      }
    };
  },
  watch: {
    dateRange () {
      if (this.dateRange[0]) {
        // if ((this.dateRange[0].toJSON().substring(0, 10) + '—' + this.dateRange[1].toJSON().substring(0, 10)) !== this.monthDateRange) {
        // this.monthDateRange = null;
        // }
        this.billingCycle = this.dateRange[0].Format('yyyyMMdd') + '-' + this.dateRange[1].Format('yyyyMMdd');
      }
    },
    // monthDateRange () {
    // if (this.monthDateRange) {
    // this.dateRange = [new Date(this.monthDateRange.split('—')[0]), new Date(this.monthDateRange.split('—')[1])];
    // }
    // },
    totalIncomeInfo () {
      if (this.totalIncomeInfo.truckBellwetherTflowIds[0]) {
        this.isAbleToOpenChargeOffs = false;
      } else {
        this.isAbleToOpenChargeOffs = true;
      }
    }
  },
  methods: {
    //  获取一年内的所有月份区间数组
    getAllMonthDateRange () {
      let arr = [];
      const today = new Date('2018-05-06');
      let year = today.getFullYear();
      let month = today.getMonth();
      if (month === 0) {
        year = year - 1;
        for (let i = 0; i < 12; i++) {
          let monthNew = i + 1;
          if (monthNew < 10) {
            monthNew = '0' + monthNew;
          }
          let firstDay = year + '-' + monthNew + '-01';
          let myDate = new Date(year, monthNew, 0);
          let lastDay = year + '-' + monthNew + '-' + myDate.getDate();
          arr.push({'label': year + '年' + monthNew + '月', 'value': firstDay + '—' + lastDay});
        }
      } else {
        let yearPre = year - 1;
        for (let i = month; i < 12; i++) {
          let monthNew = i + 1;
          if (monthNew < 10) {
            monthNew = '0' + monthNew;
          }
          let firstDay = yearPre + '-' + monthNew + '-01';
          let myDate = new Date(yearPre, monthNew, 0);
          let lastDay = yearPre + '-' + monthNew + '-' + myDate.getDate();
          arr.push({'label': yearPre + '年' + monthNew + '月', 'value': firstDay + '—' + lastDay});
        }
        for (let i = 0; i < month; i++) {
          let monthNew = i + 1;
          if (monthNew < 10) {
            monthNew = '0' + monthNew;
          }
          let firstDay = year + '-' + monthNew + '-01';
          let myDate = new Date(year, monthNew, 0);
          let lastDay = year + '-' + monthNew + '-' + myDate.getDate();
          arr.push({'label': year + '年' + monthNew + '月', 'value': firstDay + '—' + lastDay});
        }
      }
      arr.reverse();
      return arr;
    },
    // 图片上传
    // 图片数量控制
    handleExceed () {
      this.$message.warning('最多只能上传5张图片');
    },
    // 图片大小格式限制
    beforeUploadImg (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if (!isJPG) {
        this.$message.error('上传线路图片只能是 JPG 和 png格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传线路图片大小不能超过 10MB!');
      }
      return isJPG && isLt10M;
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片列表改变
    handleChange (file, fileList) {
      this.fileList = fileList;
    },
    // 移除图片
    handleRemove (file, fileList) {
      this.fileList = fileList;
    },
    // 关闭可销账列表窗口
    closeChargeOffsList () {
      this.dialogVisible = false;
    },
    // 关闭销账窗口
    closeInfoChargeOffs () {
      this.isList = true;
    },
    // 销账操作窗口
    openChargeOffs () {
      if (!this.dateRange[0]) {
        this.$message.error('请选择销账日期');
        return;
      }
      this.isList = false;
      this.objInfo = {
        // 'truckBellwetherTflowIds': this.totalIncomeInfo.truckBellwetherTflowIds, // 可销账收益明细id
        'truckBellwetherId': this.truckBellwetherId,
        'chargeOffsTime': null, // 销账时间
        'billingCycle': this.billingCycle, // 账单周期
        'chargeOffsAmount': this.totalIncomeInfo.totalIncomeAmt, // 销账金额
        'bankName': null, // 到账银行
        'bankNum': null, // 银行卡号
        'accountName': null, // 银行户名
        'serialNum': null, // 流水号
        'remark': null, // 备注
        'transVoucherUrl': null // 交易凭证（图片url）
      };
    },
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchTableList();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchTableList();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchTableList();
    },
    // 重置查询条件
    resetSearchCondition () {
      resetObjNull(this.searchCondition);
      this.dateRange = [];
      // this.monthDateRange = null;
    },
    // 查询列表执行
    loadingLists (filter = '') {
      this.listLoading = true;
      searchTruckBellwetherAcctTFlowList({
        filters: filter,
        size: this.pageSize,
        page: this.currentPage - 1,
        sort: this.sortProp === null ? 'createdDate,desc' : (this.sortProp + (this.sortOrder === 'ascending' ? ',asc' : ',desc'))
      }).then(res => {
        this.tableData = res.data;
        this.total = Number(res.headers['x-total-count']);
        this.listLoading = false;
      });
    },
    // 查询统计
    sumLoadingLists (filter = '') {
      searchTruckBellwetherAcctTFlowListSum({filters: filter}).then(res => {
        this.totalIncomeInfo = res.data;
      });
    },
    toFilters () {
      let filters = 'EQ_writeOffStatus=102019004;EQ_truckBellwether.id=' + this.truckBellwetherId;
      if (this.dateRange[0]) {
        filters += ';GTE_truckLoadOrder.unloadTime=' + this.dateRange[0].toJSON();
        filters += ';LTE_truckLoadOrder.unloadTime=' + this.$ue.addDays(this.dateRange[1], 1).toJSON();
      };
      return filters;
    },
    // 查询调用
    searchTableList () {
      this.loadingLists(this.toFilters());
      this.sumLoadingLists(this.toFilters());
    },
    handleSubmit () {
      // 表单验证
      this.$refs['objInfo'].validate((valid) => {
        if (valid) {
          if (!this.fileList[0]) {
            this.$message.error('请上传凭证！');
          };
          let urlList = this.fileList.map(item => item.response);
          this.objInfo.transVoucherUrl = urlList.join(',');
          this.submitLoading = true;
          let TruckBellwetherWriteOffCreateVO = {
            'truckBellwetherTflowIds': this.totalIncomeInfo.truckBellwetherTflowIds,
            'truckBellwetherWriteOffDTO': this.objInfo
          };
          saveTruckBellwetherWriteOff(TruckBellwetherWriteOffCreateVO).then((res) => {
            this.isList = true;
            this.$message.success('销账成功');
            // 刷新收益统计表
            this.dialogVisible = false;
            this.$emit('comfirmSuccess');
          }).catch((res) => {
            this.$message.error(res.response.data.message);
          });
          this.submitLoading = false;
        } else {
          return false;
        }
      });
    },
    show (bellwetherId, truckBellwetherName) {
      this.dialogVisible = true;
      this.truckBellwetherId = bellwetherId;
      this.truckBellwetherName = truckBellwetherName;
      this.resetSearchCondition();
      this.dateRange = this.$ue.getPreMonthDateRange();
      // this.allMonthDateRange = this.getAllMonthDateRange();
      this.searchTableList();
    }
  },
  mounted () {}
};
</script>
